package com.example.scaffold_demo.http.download;

import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;


import com.example.httplibrary.download.DownLoadCallBack;
import com.example.httplibrary.download.DownLoadManagerToos;
import com.example.scaffold_demo.BaseApplication;
import com.example.scaffold_demo.R;
import com.example.scaffold_demo.common.Constant;
import com.example.scaffold_demo.common.EventConstant;
import com.example.scaffold_demo.ui.DownloadActivity;
import com.example.scaffold_demo.utils.SPUtils;
import com.example.scaffold_demo.widget.eventbus.EventBean;
import com.example.scaffold_demo.widget.eventbus.EventBusUtil;

import java.io.File;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import static android.app.Notification.VISIBILITY_SECRET;

/**
 * Author: 李巷阳
 * Date: 2020/9/7
 * Description: 下载apk service
 */
public class DownloadApkService extends IntentService {

    private static final String TAG = "DownloadIntentService";
    private NotificationManager mNotifyManager;
    private String mDownloadFileName;
    private Notification mNotification;
    private int notifyId;
    public static final String CHANNEL_ID = "moego";
    private static final String CHANNEL_NAME = "Download_moego";
    public static final String DOWNLOAD_TYPE = "type";
    public static final String DOWNLOAD_PAUSE = "pause";


    private NotificationCompat.Builder builder;
    private int isOpenmNotify;// 是否打开通知栏 0不打开  1打开

    public DownloadApkService() {
        super("InitializeService");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

        String status = intent.getStringExtra(DOWNLOAD_TYPE);
        if (DOWNLOAD_PAUSE.equals(status)) {
            if (mNotifyManager != null) {
                mNotifyManager.cancel(notifyId);
            }
            // 暂定下载
            DownLoadManagerToos.getInstance().setStop(true);
        }

        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        String downloadUrl = intent.getExtras().getString(DownloadActivity.INTENT_DOWNLOAD_URL);
        notifyId = intent.getExtras().getInt(DownloadActivity.INTENT_NOTIFY_ID);
        mDownloadFileName = intent.getExtras().getString(DownloadActivity.INTENT_DOWNLOAD_FILE_NAME);
        isOpenmNotify = intent.getExtras().getInt(DownloadActivity.INTENT_IS_OPEN_NOTIFY);

        if (downloadUrl == null ) {
            return;
        }
        Log.d(TAG, "download_url --" + downloadUrl);
        Log.d(TAG, "download_file --" + mDownloadFileName);
        String loadFilePath = Constant.DEFAULT_DOWNLOAD_PATH + "/" + mDownloadFileName;
        final File file = new File(loadFilePath);
        // 本地下载文件range
        long load_range = 0;
        // 本地文件下载进度
        int load_progress = 0;
        if (file.exists()) {
            load_range = (long) SPUtils.get(downloadUrl, 0L);
            load_progress = (int) (load_range * 100 / file.length());
            if (load_range == file.length() ) {
                installApp(file);
                return;
            }
        }
        final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify_download);
        remoteViews.setProgressBar(R.id.pb_progress, 100, load_progress, false);
        remoteViews.setTextViewText(R.id.tv_progress, "萌股正在下载中...(" + load_progress + "%)");

        Log.d(TAG, "range = " + load_range);

        // isOpenmNotification 0 不打开通知栏  1打开通知栏
        if (isOpenmNotify == 1) {
            // 添加通知栏 的关闭时的 点击事件
            Intent goneIntent = new Intent(this, DownloadApkService.class);
            Bundle mBundle = new Bundle();
            mBundle.putString(DOWNLOAD_TYPE, DOWNLOAD_PAUSE);
            goneIntent.putExtras(mBundle);
            PendingIntent canclePendingIntent = PendingIntent.getService(this, 0, goneIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.iv_dismiss, canclePendingIntent);


            final Bitmap largeIcon = ((BitmapDrawable) getResources().getDrawable(R.mipmap.logo)).getBitmap();


            mNotifyManager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //android 8.0以上需要特殊处理，也就是targetSDKVersion为26以上
                createNotificationChannel();
                builder =
                        new NotificationCompat.Builder(this, CHANNEL_ID)
                                .setContent(remoteViews)
//                                .setContentIntent(getDefalutIntent(Notification.FLAG_FOREGROUND_SERVICE))
                                .setPriority(NotificationCompat.PRIORITY_HIGH)//设置该通知优先级
                                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
//                        .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
                                .setTicker("正在下载")
                                .setLargeIcon(largeIcon)
                                .setAutoCancel(false)
                                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
                                .setVibrate(new long[]{0})
                                .setSound(null)
                                .setSmallIcon(R.mipmap.logo);

            } else {
                builder =
                        new NotificationCompat.Builder(this)
                                .setContent(remoteViews)
//                                .setContentIntent(getDefalutIntent(Notification.FLAG_FOREGROUND_SERVICE))
                                .setPriority(NotificationCompat.PRIORITY_HIGH)//设置该通知优先级
                                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
//                        .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
                                .setTicker("正在下载")
                                .setLargeIcon(largeIcon)
                                .setAutoCancel(false)
                                .setSmallIcon(R.mipmap.logo);
            }


            mNotification = builder.build();
            mNotifyManager.notify(notifyId, mNotification);

        }

        DownLoadManagerToos.getInstance().downloadFile(getApplicationContext(),load_range, downloadUrl, mDownloadFileName, Constant.DEFAULT_DOWNLOAD_PATH, new DownLoadCallBack() {
            @Override
            public void onProgress(int progress) {
                EventBusUtil.sendEvent(new EventBean(EventConstant.VersionUpdateProgressBar, progress));
                // isOpenmNotification 0 不打开通知栏  1打开通知栏
                if (isOpenmNotify == 1) {
                    remoteViews.setProgressBar(R.id.pb_progress, 100, progress, false);
                    remoteViews.setTextViewText(R.id.tv_progress, "萌股正在下载中...(" + progress + "%)");
                    mNotifyManager.notify(notifyId, mNotification);
                }
            }

            @Override
            public void onCompleted() {
                Log.d(TAG, "下载完成");
                Toast.makeText(DownloadApkService.this, "萌股安装包下载成功", Toast.LENGTH_SHORT).show();
                if (mNotifyManager != null) {
                    mNotifyManager.cancel(notifyId);
                }
                installApp(file);
            }

            @Override
            public void onError(String msg) {
                if (mNotifyManager != null) {
                    mNotifyManager.cancel(notifyId);
                }
                Toast.makeText(DownloadApkService.this, "下载发生错误--", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStop() {
                stopSelf();
            }
        });
    }

    /**
     * 安装app
     * @param apkFile
     */
    private void installApp(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.scaffold_demo.fileprovider", apkFile);//通过FileProvider创建一个content类型的Uri
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (BaseApplication.getContext().getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            BaseApplication.getContext().startActivity(intent);
        }
    }


    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        channel.canBypassDnd();//是否绕过请勿打扰模式
        channel.enableLights(false);//闪光灯
        channel.setLockscreenVisibility(VISIBILITY_SECRET);//锁屏显示通知
        channel.setLightColor(Color.RED);//闪关灯的灯光颜色
        channel.canShowBadge();//桌面launcher的消息角标
        channel.enableVibration(false);//是否允许震动
//        channel.getAudioAttributes();//获取系统通知响铃声音的配置
        channel.getGroup();//获取通知取到组
        channel.setSound(null,null);
        channel.setBypassDnd(true);//设置可绕过 请勿打扰模式
//        channel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式
        channel.shouldShowLights();//是否会有灯光
        mNotifyManager.createNotificationChannel(channel);
    }

}
